package edu.vt.ece.rt.quorum.util;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import edu.vt.ece.rt.dstm.QObject;
import edu.vt.ece.rt.util.Logger.Logger;

/*
 * This class is used to synchronise the message received in response of ReadRequest
 * @author Sudhanshu
 */
public class ReplyObjectStore {
	AtomicInteger counter;
	public boolean requestFail=true;		//To determine whether request failed 
	/*
	 * Use priority as version object, QObject is already comparable
	 */
	PriorityBlockingQueue<QObject> objList;			//FIXME: Might require change
	
	public ReplyObjectStore(int c){
		counter = new AtomicInteger(c);
		objList = new PriorityBlockingQueue<QObject>();
	}
	
	public void processMessage(Object obj){
		if(obj !=null)
			objList.add((QObject) obj);
		
		if(counter.decrementAndGet() == 0){
			//MeansYou are last reply
			requestFail = false;
			synchronized (this) {
				this.notifyAll();				//Notify all threads waiting on it				
			}
			Logger.debug("Notified the wait read thread");
		}
	}
	
	/*
	 * Latest version is highest version, head on priority queue
	 */
	public QObject findLatest(){
		return objList.peek();
	}
}
